import json
from core.client import APIClient
from config.settings import Config


class AuthManager:
    """认证管理器，处理登录和token管理"""
    
    def __init__(self, client: APIClient):
        self.client = client
        self.token = None
    
    def login(self, account: str, password: str) -> str:
        """用户登录并获取token"""
        login_data = {
            'clientType': Config.FIXED_PARAMS['clientType'],
            'address': 'https://www.iqihang.com/ark/exam26',
            'browser': Config.FIXED_PARAMS['browser'],
            'browserVersion': Config.FIXED_PARAMS['browserVersion'],
            'loginAddress': '',
            'loginProduct': Config.FIXED_PARAMS['source'],
            'loginTerminal': Config.FIXED_PARAMS['terminal'],
            'loginType': Config.FIXED_PARAMS['loginType'],
            'loginVersion': '1.0.0',
            'network': '',
            'networkType': '',
            'os': Config.FIXED_PARAMS['os'],
            'osVersion': Config.FIXED_PARAMS['osVersion'],
            'plant': '',
            'plantType': '',
            'source': Config.FIXED_PARAMS['source'],
            'sourceType': Config.FIXED_PARAMS['sourceType'],
            'terminal': Config.FIXED_PARAMS['terminal'],
            'version': '1.0.0',
            'account': account,
            'password': password,
        }
        
        response = self.client.post(Config.API_ENDPOINTS['login'], json_data=login_data)
        data = response.json()
        
        if data['code'] == 0:
            self.token = f"Bearer {data['data']['token']}"
            print("\033[1;32m登录成功！！\033[0m")
            return self.token
        else:
            raise ValueError(f"登录失败：{data['msg']}")
    
    def get_auth_headers(self):
        """获取包含认证信息的请求头"""
        headers = Config.DEFAULT_HEADERS.copy()
        if self.token:
            headers['authorization'] = self.token
        return headers